﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace AchieveCommon
{
    public class ImgHelper
    {
        private const double PI = 3.1415926535897932384626433832795;
        private const double PI2 = 5.583185307179586476925286766559;
        /// <summary>
        ///  返回图片
        /// </summary>
        /// <param name="checkCode"></param>
        /// <returns></returns>
        public System.Drawing.Bitmap CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return null;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 15.0)), 25);
            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成随机生成器
                Random random = new Random();

                //清空图片背景色
                g.Clear(Color.White);

                //画图片的背景噪音线
                for (int i = 0; i < 20; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                Font font = new System.Drawing.Font("Arial", 16, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);

                //画图片的前景噪音点
                for (int i = 0; i < 130; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                image = TwistImage(image, true, 3, 1);//画图片的波形滤镜效果
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                return image;
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        /// <summary>
        /// 生成文字
        /// </summary>
        /// <returns></returns>
        public string GenerateCheckCode(int maxlength)
        {
            int number;
            char code;
            string checkCode = String.Empty;

            System.Random random = new Random();

            for (int i = 0; i < maxlength; i++)
            {
                number = random.Next();

                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));
                else
                    code = (char)('A' + (char)(number % 26));

                checkCode += code.ToString();
            }
            return checkCode;
        }

        /// <summary>
        /// 画图片的波形滤镜效果
        /// </summary>
        /// <param name="srcBmp"></param>
        /// <param name="bXDir"></param>
        /// <param name="dMultValue"></param>
        /// <param name="dPhase"></param>
        /// <returns></returns>
        public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

            // 将位图背景填充为白色
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();

            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;
                    dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
                    dx += dPhase;
                    double dy = Math.Sin(dx);

                    // 取得当前点的颜色
                    int nOldX = 0, nOldY = 0;
                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    System.Drawing.Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width
                     && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }

            return destBmp;
        }

        //image和byte[]的互相转换
        //参数是图片的路径
        public byte[] GetPictureData(string imagePath)
        {
            FileStream fs = new FileStream(imagePath, FileMode.Open);
            byte[] byteData = new byte[fs.Length];
            fs.Read(byteData, 0, byteData.Length);
            fs.Close();
            return byteData;
        }
        //将Image转换成流数据，并保存为byte[] 
        public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto)
        {
            MemoryStream mstream = new MemoryStream();
            imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] byData = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(byData, 0, byData.Length); mstream.Close();
            return byData;
        }
        //参数是Byte[]类型，返回值是Image对象
        public System.Drawing.Image ReturnPhoto(byte[] streamByte)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            return img;
        }
        //参数是Byte[] 类型，没有返回值（ASP.NET输出图片）
        //public void WritePhoto(byte[] streamByte)
        //{
        //    // Response.ContentType 的默认值为默认值为“text/html”
        //    Response.ContentType = "image/GIF";
        //    //图片输出的类型有: image/GIF     image/JPEG
        //    Response.BinaryWrite(streamByte);
        //}

        /// <summary>
        /// 将Tif格式转Jpg，磁盘文件到文件
        /// </summary>
        /// <param name="tiffFileName"></param>
        /// <param name="jpegFileName"></param>
         public void ConvertTiff2Jpeg(string tiffFileName, string jpegFileName)
        {
            var img = Image.FromFile(tiffFileName);
            var count = img.GetFrameCount(FrameDimension.Page);
            for (int i = 0; i < count; i++)
            {
                img.SelectActiveFrame(FrameDimension.Page, i);
                img.Save(jpegFileName + ".part" + i + ".jpg");
            }
            int imageWidth = img.Width;
            int imageHeight = img.Height * count;
            Bitmap joinedBitmap = new Bitmap(imageWidth, imageHeight);
            Graphics graphics = Graphics.FromImage(joinedBitmap);
            for (int i = 0; i < count; i++)
            {
                var partImageFileName = jpegFileName + ".part" + i + ".jpg";
                Image partImage = Image.FromFile(partImageFileName);
                graphics.DrawImage(partImage, 0, partImage.Height * i, partImage.Width, partImage.Height);
                partImage.Dispose();
                File.Delete(partImageFileName);
            }
            joinedBitmap.Save(jpegFileName);

            graphics.Dispose();
            joinedBitmap.Dispose();
            img.Dispose();

            //return jpegFileName;
        }

         /// <summary>
         /// 将Tif格式转Jpg，内存到内存
         /// </summary>
         /// <param name="tiffFileName"></param>
         /// <param name="jpegFileName"></param>
         public static Bitmap  ConvertTiff2Jpg(byte[] TifImg)
         {
             System.IO.MemoryStream ms = new System.IO.MemoryStream(TifImg);
             System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
             ms.Dispose();
             var count = img.GetFrameCount(FrameDimension.Page);
             List<MemoryStream> mmlist = new List<MemoryStream>();
             //MemoryStream[] mm=new MemoryStream[count];            
             for (int i = 0; i < count; i++)
             {
                 MemoryStream mm = new MemoryStream();
                 img.SelectActiveFrame(FrameDimension.Page, i);
                 img.Save(mm, ImageFormat.Bmp);
                 mmlist.Add(mm);
             }     
            
             int imageWidth = img.Width;
             int imageHeight = img.Height * count;
             Bitmap joinedBitmap = new Bitmap(imageWidth, imageHeight);
             Graphics graphics = Graphics.FromImage(joinedBitmap);
             for (int i = 0; i < count; i++)
             {
                 Image partImage = Image.FromStream(mmlist[i]);                 
                 graphics.DrawImage(partImage, 0, partImage.Height * i, partImage.Width, partImage.Height);
             }
             foreach (MemoryStream item in mmlist)
             {
                 item.Dispose();
             }
             return joinedBitmap;
             //MemoryStream ms0 =new MemoryStream();
             //joinedBitmap.Save(ms0, ImageFormat.Jpeg);
             //ms0.Seek(0, SeekOrigin.Begin);
             //byte[] bytes = new byte[ms0.Length];
             //ms0.Read(bytes, 0, bytes.Length);
             //ms0.Dispose();
             //return bytes;            
         }

    }
}
